#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "mpi.h"

int
main(int argc, char **argv)
{
	int size, rank;
	int i=0;
	int *sendbuf, *displs, *rcounts;
	int *recvbuf;
	int success = 1;
	printf("before init\n");
	
	MPI_Init(&argc, &argv);
	
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);

	printf("Size %d, Rank %d\n",size,rank);
	
	sendbuf = (int *)malloc(sizeof(int) * size);
	rcounts = (int *)malloc(sizeof(int) * size);
	displs = (int *)malloc(sizeof(int) * size);

	recvbuf = (int *)malloc(size*sizeof(int) * size); 

	for( i = 0; i < size; i++ )
        {
		sendbuf[i] = i + 1;
	}
	
	for( i = 0; i < size; i++ )
        {
//                sendbuf[i] = i;
		rcounts[i] = 2;
		displs[i]  = i * 2;
        }

	if( rank == 0 )
	{
		MPI_Gatherv(sendbuf,size,MPI_INT,recvbuf,rcounts,displs, MPI_INT, 0,MPI_COMM_WORLD);
		for (i = 0; i < size*2; i++) {
			if (i % 2 == 0) {
				printf("GatherV_RECV: recvbuf[%d]: %d recvbuf[%d]: %d\n",
						i, recvbuf[i], i+1, recvbuf[i+1]);
				success = success && (recvbuf[i] == 1);
			} else {
				success = success && (recvbuf[i] == 2);
			}

		}
		if (success == 1) {
			printf("SUCCESS\n");
		}
	}
	else 
	{
//		sendbuf[0] = 1;
//		sendbuf[1] = 2;
		MPI_Gatherv(sendbuf,size,MPI_INT,recvbuf, rcounts,displs, MPI_INT, 0, MPI_COMM_WORLD);
		printf("SEND: sendbuf[0]: %d sendbuf[1]: %d\n", sendbuf[0], sendbuf[1]);
	}
	

	MPI_Finalize();
	return 0;
}

